import cn.org.rapid_framework.generator.GeneratorFacade;
import cn.org.rapid_framework.generator.GeneratorProperties;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;


/**
 * @author KingViker qq：413041153
 */
public class GeneratorJFrame extends JFrame {
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private JTextField tableNameInput;
    private JTextField modulNameInput;
    private JTextField classNameInput;
    private JTextField datasourceNameInput;
    private JComboBox idStrategyInput;
    private JTextArea messageArea;
    private JButton generatorBtn;
    private PrintStream ps;

    public GeneratorJFrame() {
        super("rapid-genterator by KingViker");
        initComponents();
    }

    public static void main(String[] args) {
        new GeneratorJFrame().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ;
    }

    private void initComponents() {
        Font f = new Font("宋体", Font.PLAIN, 15);

        UIManager.put("Label.font", f);
        UIManager.put("Button.font", f);

        Container contentPane = getContentPane();
        JPanel panel = new JPanel();
        panel.setLayout(null);


        tableNameInput = new JTextField();
        JLabel tableName = new JLabel("数据库表名称：");
        tableName.setBounds(20, 10, 180, 25);
        panel.add(tableName);
        tableNameInput.setBounds(210, 10, 160, 25);
        tableNameInput.setText("tbl_");
        panel.add(tableNameInput);

        modulNameInput = new JTextField();
        JLabel modulName = new JLabel("模块名称：");
        modulName.setBounds(20, 40, 180, 25);
        panel.add(modulName);
        modulNameInput.setBounds(210, 40, 160, 25);
        panel.add(modulNameInput);

        classNameInput = new JTextField();
        JLabel className = new JLabel("数据库表名称映射的类名：");
        className.setBounds(20, 70, 180, 25);
        panel.add(className);
        classNameInput.setBounds(210, 70, 160, 25);
        panel.add(classNameInput);

        datasourceNameInput = new JTextField();
        JLabel datasourceName = new JLabel("数据源代号(如one,two)：");
        datasourceName.setBounds(20, 100, 180, 25);
        panel.add(datasourceName);
        datasourceNameInput.setText("one");
        datasourceNameInput.setBounds(210, 100, 160, 25);
        panel.add(datasourceNameInput);

        String[] str = {"自增", "手工"};
        idStrategyInput = new JComboBox(str);
        JLabel hasPermission = new JLabel("ID策略：");
        hasPermission.setBounds(20, 130, 180, 25);
        panel.add(hasPermission);
        idStrategyInput.setBounds(210, 130, 160, 25);
        panel.add(idStrategyInput);

        //信息展示窗口
        messageArea = new JTextArea();
        messageArea.setBounds(20, 200, 355, 150);
        JScrollPane jsp = new JScrollPane(messageArea);
        jsp.setBounds(20, 200, 355, 150);
        panel.add(jsp);
        //将项目system.out指定到messageArea，这样项目中的打印功能，都会打印到messageArea中
        ps = new PrintStream(System.out) {
            @Override
            public void println(String x) {
                messageArea.append(x + "\n");
            }
        };
        System.setOut(ps);

        generatorBtn = new JButton();
        generatorBtn.setText("生成");
        generatorBtn.setBounds(100, 160, 80, 30);
        generatorBtn.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                generatorBtnActionPerformed(evt);
            }
        });

        panel.add(generatorBtn);

        JButton exitBtn = new JButton("退出");
        exitBtn.setBounds(220, 160, 80, 30);
        exitBtn.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                System.exit(0);
            }
        });
        panel.add(exitBtn);

        contentPane.add(panel);
        double width = Toolkit.getDefaultToolkit().getScreenSize().getWidth();
        double height = Toolkit.getDefaultToolkit().getScreenSize().getHeight();
        this.setLocation((int) (width - this.getWidth()) / 2 - 175, (int) (height - this.getHeight()) / 2 - 150);
        this.setSize(400, 390);
        this.setVisible(true);
        this.setResizable(false);

    }

    private void generatorBtnActionPerformed(ActionEvent evt) {
        if (StringUtils.isBlank(tableNameInput.getText())) {
            JOptionPane.showMessageDialog(this, "请输入表名称！");
            return;
        }
        if (StringUtils.isBlank(modulNameInput.getText())) {
            String tableNamePrefix = GeneratorProperties.getProperty("tableRemovePrefixes");
            modulNameInput.setText(tableNameInput.getText().substring(tableNamePrefix.length()).toLowerCase());
        }
        if (StringUtils.isBlank(classNameInput.getText())) {
            String tableNamePrefix = GeneratorProperties.getProperty("tableRemovePrefixes");
            classNameInput.setText(StringUtils.capitalize(tableNameInput.getText().substring(tableNamePrefix.length()).toLowerCase()));
        }
        if (StringUtils.isBlank(datasourceNameInput.getText())) {
            datasourceNameInput.setText("one");
        }
        GeneratorFacade facade = new GeneratorFacade();
        System.setProperty("modulName", modulNameInput.getText().trim());
        System.setProperty("className", classNameInput.getText().trim());
        System.setProperty("datasourceName", datasourceNameInput.getText().trim());
        System.setProperty("idStrategy", (String) idStrategyInput.getSelectedItem());

        System.setProperty("model_package", GeneratorProperties.getProperty("namespace") + "." + modulNameInput.getText().trim() + ".model." + datasourceNameInput.getText().trim());
        System.setProperty("dao_package", GeneratorProperties.getProperty("namespace") + "." + modulNameInput.getText().trim() + ".dao." + datasourceNameInput.getText().trim());
        System.setProperty("service_package", GeneratorProperties.getProperty("namespace") + "." + modulNameInput.getText().trim() + ".service");
        System.setProperty("service_impl_package", GeneratorProperties.getProperty("namespace") + "." + modulNameInput.getText().trim() + ".service.impl");
        System.setProperty("controller_package", GeneratorProperties.getProperty("namespace") + "." + modulNameInput.getText().trim() + ".controller");
        //common包前缀
        System.setProperty("commonNamespace", GeneratorProperties.getProperty("commonNamespace"));
        //author
        System.setProperty("author", GeneratorProperties.getProperty("author"));

        try {
            String jdbcDriver = GeneratorProperties.getProperty("jdbc.driver");
            if (jdbcDriver.equals("oracle.jdbc.driver.OracleDriver")) {
                System.setProperty("databaseType", "oracle");
            } else if (jdbcDriver.equals("com.mysql.jdbc.Driver") || jdbcDriver.equals("com.mysql.cj.jdbc.Driver")) {
                System.setProperty("databaseType", "mysql");
            }


            //创建输出目录
            File outRootFunctionDir = new File(GeneratorProperties.getProperty("outRootFunction"));
            if (!outRootFunctionDir.exists()) {
                outRootFunctionDir.mkdirs();
            }
            //清空输出目录
            FileUtils.cleanDirectory(outRootFunctionDir);

            //根据模板生成代码
            facade.generateByTable(tableNameInput.getText().trim(), GeneratorProperties.getProperty("templatePath") + "noPermission");

            messageArea.append("Generate Successfully!");

            copyFileToProject(this);

            JOptionPane.showMessageDialog(this, "代码已生成！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 移动到指定的项目目录
     *
     * @throws IOException
     */
    private void copyFileToProject(Component parentComponent) throws IOException {

        String outRootProject = GeneratorProperties.getProperty("outRootProject");
        if (outRootProject != null) {

            String outRoot = GeneratorProperties.getProperty("outRootFunction") + modulNameInput.getText().trim() + File.separator;
            String modelFile = outRoot + "model" + File.separator + classNameInput.getText().trim() + ".java";
            String modelPojoFile = outRoot + "model" + File.separator + classNameInput.getText().trim() + "Pojo.java";
            String controllerFile = outRoot + "controller" + File.separator + classNameInput.getText().trim() + "Controller.java";
            String serviceFile = outRoot + "service" + File.separator + "I" + classNameInput.getText().trim() + "Service.java";
            String serviceImplFile = outRoot + "service" + File.separator + "impl" + File.separator + classNameInput.getText().trim() + "ServiceImpl.java";
            String daoFile = outRoot + "dao" + File.separator + "jpa" + File.separator + classNameInput.getText().trim() + "JpaRepository.java";


            String outBeanDir = outRootProject + GeneratorProperties.getProperty("outBeanDir");
            outBeanDir = outBeanDir.replace("#datasource#", datasourceNameInput.getText().trim());
            outBeanDir = outBeanDir.replace("#modelName#", modulNameInput.getText().trim());

            String outPojoDir = outRootProject + GeneratorProperties.getProperty("outPojoDir");
            outPojoDir = outPojoDir.replace("#modelName#", modulNameInput.getText().trim());

            String outDaoDir = outRootProject + GeneratorProperties.getProperty("outDaoDir");
            outDaoDir = outDaoDir.replace("#datasource#", datasourceNameInput.getText().trim());
            outDaoDir = outDaoDir.replace("#modelName#", modulNameInput.getText().trim());

            String outServiceDir = outRootProject + GeneratorProperties.getProperty("outServiceDir");
            outServiceDir = outServiceDir.replace("#modelName#", modulNameInput.getText().trim());

            String outServiceImplDir = outRootProject + GeneratorProperties.getProperty("outServiceImplDir");
            outServiceImplDir = outServiceImplDir.replace("#modelName#", modulNameInput.getText().trim());

            String outControllerDir = outRootProject + GeneratorProperties.getProperty("outControllerDir");
            outControllerDir = outControllerDir.replace("#modelName#", modulNameInput.getText().trim());

            final int confirmDialog = JOptionPane.showConfirmDialog(parentComponent, "是否拷贝到项目对应的文件夹？", "请确认！！！", JOptionPane.YES_NO_OPTION);
            if (confirmDialog == 0) {
                if (copyBefore(parentComponent, new File(modelFile), new File(outBeanDir))) {
                    FileUtils.copyFileToDirectory(new File(modelFile), new File(outBeanDir));
                    FileUtils.copyFileToDirectory(new File(modelPojoFile), new File(outPojoDir));
                    FileUtils.copyFileToDirectory(new File(controllerFile), new File(outControllerDir));
                    FileUtils.copyFileToDirectory(new File(serviceFile), new File(outServiceDir));
                    FileUtils.copyFileToDirectory(new File(serviceImplFile), new File(outServiceImplDir));
                    FileUtils.copyFileToDirectory(new File(daoFile), new File(outDaoDir));
                }
            }


        }
    }

    /**
     * <h2>验证目标文件是否已经存在</h2>
     * Created by hanqf on 2021/7/29 10:57.
     *
     * @author hanqf
     */
    public boolean copyBefore(Component parentComponent, File srcFile, File destDir) {
        File destFile = new File(destDir, srcFile.getName());
        if (destFile.exists()) {
            final int confirmDialog = JOptionPane.showConfirmDialog(parentComponent, "目标路径部分文件已经存在，是否完全覆盖？", "请确认！！！", JOptionPane.YES_NO_OPTION);
            if (confirmDialog == 0) {
                return true;
            } else {
                return false;
            }
        }
        return true;


    }

}
